<?php

namespace app\api\model;

use think\Model;
use traits\model\SoftDelete;

class Students extends Model
{
    use SoftDelete;
    protected $deleteTime = 'deletetime';

    protected $hidden = ['pivot', 'is_freeze', 'deletetime', 'createtime', 'updatetime'];

    protected $append = ['age_text'];

    public function getAgeTextAttr($value, $data)
    {
        $age = ceil((time() - strtotime($data['birthday'])) / (30 * 24 * 3600));
        $month = ($age % 12) ? $age % 12 . '个月' : '';
        return $data['birthday'] ? floor($age / 12) . '岁' . $month : '';
    }

    public function getImageAttr($value)
    {
        return $value ? request()->domain().$value : '';
    }

    public function parents()
    {
        return $this->belongsToMany(Parents::class, 'parent_students', 'parent_id', 'student_id');
    }

    public function classes()
    {
        return $this->hasOne(Classes::class, 'id', 'class_id');
    }

    public static function getStudentsByIds($ids)
    {
        return self::whereIn('id', $ids)->where('is_freeze', 0)->select();
    }

    public static function getStudentsByClassIds($class_ids)
    {
        return self::whereIn('class_id', $class_ids)->where('is_freeze', 0)->select();
    }

    public static function getStudentByUser($user_id)
    {
        $user = Users::find($user_id);
        $student = [];
        if ($user) {
            $student = self::where('telphone', $user->phone)->where('is_freeze', 0)->find();
        }
        return $student;
    }

    public static function getClassId($id)
    {
        return self::where('id', $id)->value('class_id');
    }

    public static function getStudentsByTeacher($teacher_id, $class_id, $student_name, $length = 15)
    {
        $where['is_freeze'] = ['=', 0];
        $classIds = TeacherClasses::getClassIds($teacher_id);
        if ($class_id) {
            $classIds = [$class_id];
        }
        if ($student_name)
        {
            $where['username'] = ['like', "%{$student_name}%"];
        }
        $students = self::with(['classes', 'parents'])->where($where)->whereIn('class_id', $classIds)->paginate($length);
        foreach ($students->items() as $val) {
            $parents = array_column($val['parents'], 'id');
            $count = Friends::getFriendCounts($parents);
            $val['friend_counts'] = $count;
            unset($val['parents']);
        }
        return $students;
    }

    /**
     * 学生详情
     */
    public static function getStudentById($student_id)
    {
        return self::with(['classes', 'parents'])->find($student_id);
    }

    /**
     * 家长id
     */
    public static function getParentIds($student_id)
    {
        $students = self::getStudentById($student_id);
        return $students ? array_column($students['parents'], 'id') : [];
    }


}
